package com.shuiyun.chat.utils;

import cn.hutool.core.util.ObjectUtil;
import com.google.gson.Gson;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.ListOperations;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;

/**
 * @author shuiyun
 * @program chatServer
 * @description redis工具类
 * @create 2021-05-14 15:49
 **/
@Component
public class RedisUtil {

    private final static String KEY_HEADER = "chat:";

    @Resource(name="redisTemplate")
    private ValueOperations<String, String> valueOperations;
    @Resource(name="redisTemplate")
    private HashOperations<String, String, Object> hashOperations;
    @Resource(name="redisTemplate")
    private ListOperations<String, Object> listOperations;

    /**
     * 从队列的右边压入数据
     * @param key 键
     * @param value 值
     * @author shuiyun
     * @date 2021/5/14 15:52
     * @return 插入数据的条数
     */
    public void rightPush(String key,Object value){
        listOperations.rightPush(KEY_HEADER + key, value);
    }

    /**
     * 从队列的左边弹出数据
     * @param key 键
     * @author shuiyun
     * @date 2021/5/14 15:53
     * @return 弹出的数据 可能为空
     */
    public <T> T leftPop(String key,Class<T> clazz){
        Object o = listOperations.leftPop(KEY_HEADER + key);
        if (ObjectUtil.isNull(o)){
            return null;
        }
        T t = new Gson().fromJson(o.toString(), clazz);
        return t;
    }



}
